import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, ScanCommand, UpdateCommand } from "@aws-sdk/lib-dynamodb";
import { BookNote } from "../types";

// const client = new DynamoDBClient({
//   region: process.env.AWS_REGION,
//   credentials: {
//     accessKeyId: process.env.AWS_ACCESS_KEY_ID!,
//     secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY!,
//   },
// });

const client = new DynamoDBClient({
  region: "local",
  endpoint: "http://localhost:8000", // Local DynamoDB endpoint
  credentials: {
    accessKeyId: "AKIA6Q3XVTJRVFPPHWX4",
    secretAccessKey: "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",
  },
});

const docClient = DynamoDBDocumentClient.from(client);

export async function getBooksByCategory(category: string): Promise<BookNote[]> {
  const command = new ScanCommand({
    TableName: "book-notes",
    FilterExpression: "category = :category",
    ExpressionAttributeValues: {
      ":category": category,
    },
  });

  try {
    const response = await docClient.send(command);
    return response.Items as BookNote[];
  } catch (error) {
    console.error("Error fetching books:", error);
    throw error;
  }
}

export async function updateBookNote(bookId: string, note: string) {
  const command = new UpdateCommand({
    TableName: "book-notes",
    Key: {
      id: bookId,
    },
    UpdateExpression: "set note = :note",
    ExpressionAttributeValues: {
      ":note": note,
    },
    ReturnValues: "ALL_NEW",
  });

  try {
    const response = await docClient.send(command);
    return response.Attributes as BookNote;
  } catch (error) {
    console.error("Error updating note:", error);
    throw error;
  }
} 


export async function getBookById(id: string): Promise<BookNote> {
  const command = new ScanCommand({
    TableName: "book-notes",
    FilterExpression: "id = :id",
    ExpressionAttributeValues: {
      ":id": id,
    },
  });

  try {
    const response = await docClient.send(command);
    return response.Items?.[0] as BookNote;
  } catch (error) {
    console.error("Error fetching books:", error);
    throw error;
  }
}